<?php
if ( !defined("SCRIPT_DIR") ) {
	define("SCRIPT_DIR", dirname(__FILE__));
}
$path = explode('/',__FILE__);

if ( !defined("FILE") ) {
	define("FILE",end($path));
}

function path_format($file) {
	return SCRIPT_DIR . '/' . $file;
}


include_once(path_format('lib/logger.php'));
include_once(path_format('config/config.php'));
include_once(path_format('lib/mysql.php'));
include_once(path_format('lib/redis.php'));

class SyncConf {
	public static $sync_sec = 5;//回写数据库时间
	public static $hlen = 20;
	public static $logout_diff = 604800; //86400秒 = 一天， logout_diff时间内无活动删除redis  857019
	public static $begin = 0;
	public static $end = 0;//
}

function sync(){
	$redis = new RedisDriver();
    $ret = $redis->initCacheRedis();
    if (!$ret) {
	Config::$loggerError->error(FILE, "initCacheRedis error");
    }
	$mysql = new MysqlDriver ();
	$rets = $mysql->connect ( Config::$mysql_config );
	if (! $rets) {
		Config::$loggerError->error ( FILE, "connect mysql error." );
	}

	//把redis背包数据回写到数据库
	$key =  $redis->cache_redis->keys("hbackpack:*");
	foreach($key as $k=>$v){
		$list =  $redis->cache_redis->hGetAll($v);
        $result = $mysql->query("select id from backpack where uid=".$list['uid']." and propid=".$list['propid']);
		if ($result) {
		    $row = mysql_fetch_assoc($result);
	    }
		if(isset($row['id']) && $row['id']){
		    $mysql->query("update backpack set uid=".$list['uid'].",propid=".$list['propid'].",count=".$list['count'].",createtime=".$list['createtime'].",status=".$list['status']." where id=".$row[ 'id']);
		}else{
			$mysql->query("insert backpack (uid,propid,count,createtime,status) values(".$list['uid'].",".$list['propid'].",".$list['count'].",".$list['createtime'].",".$list['status'].")");
		}
	}
	
	
	//把redis邮件数据回写到数据库
	$key =  $redis->cache_redis->keys("hemailbyuser:*");
    for($i=0;$i<count($key);$i++){
		$id = end(explode(':',$key[$i]));
		$list = $redis->cache_redis->hGetAll($key[$i]);
		$result = $mysql->query('select * from emailbyuser where uid='.$list['uid'].' and id='.$id);
        if($result) {
		    $row = mysql_fetch_assoc($result);
		}
		$data = array(
		    'id'=>$id,
			'uid'=>$list['uid'],
			'mid'=>$list['mid'],
			'is_read'=>$list['is_read'],
			'is_receive'=>$list['is_receive'],
			'send_date'=>$list['send_date'],
			'update_date'=>$list['update_date'],
			'sender'=>$list['sender']
		);
	    if(isset($row['id']) && $row['id']){
		    $mysql->update('emailbyuser',$data,array('id'=>$row['id'],'uid'=>$list['uid']));
	    }else{
            $mysql->insert('emailbyuser',$data);
		}
	}


    $redis->deinitCacheRedis ();
	$mysql->close ();

}

function main() {
		while(1) {
		sync();	
		echo date('Y:m:d H:i:s')." ZjhSyncDumpEmailData working...\r\n"; 	
		$sync_sec = SyncConf::$sync_sec;
		sleep($sync_sec);
		
	   }
}

main ();



?>